#include "Router.h"
#include "ErrPage.h"
#include <iostream>
//std::map<std::string, std::function<std::unique_ptr<Page>(std::shared_ptr<ChangePage>)>> PageMap{};
//std::stack<std::unique_ptr<Page>> PageStack{};


void Router::Add::addPage(const std::string& key, std::function<std::unique_ptr<Page>(std::shared_ptr<ChangePage>)> factory)
{
	PageMap[key] = factory;
}

void Router::push(std::shared_ptr<ChangePage> parent, const std::string& key)
{
	auto pagePtr{ move(parent->getPage()) };
	if (nullptr != pagePtr) {
		PageStack.push(move(pagePtr));
	}
	auto it{ PageMap.find(key) };
	if (it == PageMap.end()) {
		parent->setPage(move(std::make_unique<ErrPage>(parent)));
	} else {
		parent->setPage(it->second(parent));
	}

}

void Router::replace(std::shared_ptr<ChangePage> parent, const std::string& key)
{
	if (PageMap.find(key) == PageMap.end()) {
		parent->setPage(move(std::make_unique<ErrPage>(parent)));
		return;
	}
	parent->setPage(move(PageMap[key](parent)));
}

void Router::back(std::shared_ptr<ChangePage> parent)
{
	if (PageStack.empty()) {
		return;
	}
	auto ptr{ std::move(PageStack.top()) };
	PageStack.pop();
	parent->setPage(move(ptr));
}
